-module(mock_devices_file).

-include("definitions.hrl").

-export([read_device_list_from_file/0]).

-spec read_device_list_from_file/0 :: () -> [device()].
read_device_list_from_file() ->
  case file:open("DeviceList.txt", [read]) of
    {ok, IoDevice} -> readCycle(IoDevice, []);
    _ ->
      [
        #deviceDescriptor{description = "Device1", id = 1},
        #deviceDescriptor{description = "Device2", id = 2},
        #deviceDescriptor{description = "Device3", id = 3},
        #deviceDescriptor{description = "Device4", id = 4},
        #deviceDescriptor{description = "Device5", id = 5},
        #deviceDescriptor{description = "Device6", id = 6},
        #deviceDescriptor{description = "Device7", id = 7},
        #deviceDescriptor{description = "Device8", id = 8},
        #deviceDescriptor{description = "Device9", id = 9},
        #deviceDescriptor{description = "Device10", id = 10},
        #deviceDescriptor{description = "Device11", id = 11},
        #deviceDescriptor{description = "Device12", id = 12},
        #deviceDescriptor{description = "Device13", id = 13},
        #deviceDescriptor{description = "Device14", id = 14},
        #deviceDescriptor{description = "Device15", id = 15},
        #deviceDescriptor{description = "Device16", id = 16},
        #deviceDescriptor{description = "Device17", id = 17},
        #deviceDescriptor{description = "Device18", id = 18},
        #deviceDescriptor{description = "Device19", id = 19},
        #deviceDescriptor{description = "Device20", id = 20},
        #deviceDescriptor{description = "Device21", id = 21},
        #deviceDescriptor{description = "Device22", id = 22},
        #deviceDescriptor{description = "Device23", id = 23},
        #deviceDescriptor{description = "Device24", id = 24},
        #deviceDescriptor{description = "Device25", id = 25},
        #deviceDescriptor{description = "Device26", id = 26},
        #deviceDescriptor{description = "Device27", id = 27},
        #deviceDescriptor{description = "Device28", id = 28},
        #deviceDescriptor{description = "Device29", id = 29},
        #deviceDescriptor{description = "Device30", id = 30}
      ]
  end.

-spec readCycle/2 :: (file:io_device(), [#deviceDescriptor{}]) -> [device()].
readCycle(IoDevice, Descriptors) ->
  case file:read_line(IoDevice) of
    {ok, Data} ->
      readCycle(IoDevice, [parseDevice(Data) | Descriptors]);

    {error, Reason} ->
      io:format(Reason),
      lists:reverse(Descriptors);

    eof -> lists:reverse(Descriptors)
  end.

-spec parseDevice/1 :: (string()) -> device().
parseDevice(RawPair) ->
  [Name, RawId] = string:tokens(RawPair, ",\n\r"),
  {Id, _} = string:to_integer(tl(RawId)),
  #deviceDescriptor{id = Id, description = Name}.